﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Net;

namespace TestMIC
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button1.Text = "请说话";
            button2.Text = "语音识别";
            button3.Text = "语音合成";
        }

        [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
        public static extern int mciSendString(
         string lpstrCommand,
         string lpstrReturnString,
         int uReturnLength,
         int hwndCallback
        );  

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "请说话")
            {
                mciSendString("set wave bitpersample 16", "", 0, 0);
                mciSendString("set wave samplespersec 16000", "", 0, 0);
                mciSendString("set wave channels 1", "", 0, 0);
                mciSendString("set wave format tag pcm", "", 0, 0);
                mciSendString("open new type WAVEAudio alias movie", "", 0, 0);
                mciSendString("record movie", "", 0, 0);
                button1.Text = "录音中....";
               
            }
            else 
            {
                mciSendString("stop movie", "", 0, 0);
                mciSendString("save movie 1.wav", "", 0, 0);
                mciSendString("close movie", "", 0, 0);
                button1.Text = "请说话";
               
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //获取accesstoken
            Encoding encoding = Encoding.GetEncoding("utf-8");
            string refstr = "grant_type=client_credentials&client_id=A3eKvZRHi5IGZQZ2qjgtG3ix&client_secret=IWd3zABykGG6hnWGeqeedbP0mKChxOaF";
            string rstr = ht.PostWebRequest("https://openapi.baidu.com/oauth/2.0/token", refstr, encoding, "application / json");
            JObject jo = (JObject)JsonConvert.DeserializeObject(rstr);
            string AccessToken = jo["access_token"].ToString();
            //音频文件转为base64
            string audiostr = FileToBase64("1.wav");
            audiostr = audiostr.Replace("\n", "");
           // string audiostr ="";
            //获取文件长度
            FileInfo fileInfo = new FileInfo("1.wav");
            long filelen = fileInfo.Length;
            //获取mac地址
            Computer cp=new Computer();
            string mac =cp.GetMacAddress() ;
            //拼接json字符串
            string jsonstr = "{";
            jsonstr += "\"format\":\"wav\",";
            jsonstr += "\"rate\":16000,";
            jsonstr += "\"channel\":1,";
            jsonstr += "\"token\":\"" + AccessToken + "\",";
            jsonstr += "\"cuid\":\"" + mac + "\",";
            jsonstr += "\"len\":"+filelen.ToString()+",";
            jsonstr += "\"speech\":\"" + audiostr + "\"";
            jsonstr += "}";
            //textBox1.AppendText(jsonstr);
            rstr = ht.PostWebRequest("http://vop.baidu.com/server_api", jsonstr, encoding,"application / json");
            JObject resultjson = (JObject)JsonConvert.DeserializeObject(rstr);
            string errorno = resultjson["err_no"].ToString();
            string errmsg = resultjson["err_msg"].ToString();
            string results = "";
            if (errorno.Equals("0"))
            {
                results = resultjson["result"].ToString();
                textBox1.AppendText(results);
            }
            else
            {
                textBox1.AppendText(errorno + ":" + errmsg );
            }
        }

        //文件转换为base64
        private string FileToBase64(string filepath)
        {
            string recode = "";
            System.IO.FileStream fs = System.IO.File.OpenRead(filepath);//传文件的路径即可
            System.IO.BinaryReader br = new BinaryReader(fs);
            byte[] bt = br.ReadBytes(Convert.ToInt32(fs.Length));
            string base64String = Convert.ToBase64String(bt);
            recode=base64String;
            br.Close();
            fs.Close();
            return recode;
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
            {
                ((TextBox)sender).SelectAll();
            }  
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //获取accesstoken
            Encoding encoding = Encoding.GetEncoding("utf-8");
            string refstr = "grant_type=client_credentials&client_id=A3eKvZRHi5IGZQZ2qjgtG3ix&client_secret=IWd3zABykGG6hnWGeqeedbP0mKChxOaF";
            string rstr = ht.PostWebRequest("https://openapi.baidu.com/oauth/2.0/token", refstr, encoding, "application / json");
            JObject jo = (JObject)JsonConvert.DeserializeObject(rstr);
            string AccessToken = jo["access_token"].ToString();
            //获取mac地址
            Computer cp = new Computer();
            string mac = cp.GetMacAddress();
            //传递参数
            refstr = "tex=我是小黄鸭机器人&lan=zh&cuid=" + mac + "&ctp=1&tok=" + AccessToken;
            //rstr = ht.GetUrltoHtml("http://tsn.baidu.com/text2audio?" + refstr, "utf-8");
            //下载文件 
            string ress = HttpDownloadFile("http://tsn.baidu.com/text2audio?" + refstr,"12.mp3");
            textBox1.AppendText(ress);
        }

        /// <summary>
        /// Http下载文件
        /// </summary>
        public static string HttpDownloadFile(string url, string path)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            //创建本地文件写入流
            Stream stream = new FileStream(path, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            stream.Close();
            responseStream.Close();
            return path;
        }
        
    }
}
